package com.vf.admin.miaodong.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.vf.admin.client.service.AppInvitationRecordService;
import com.vf.admin.client.service.AppMingxiJinbiService;
import com.vf.admin.client.service.AppSetupService;
import com.vf.admin.client.service.AppTaskRecordService;
import com.vf.admin.client.tx.utils.TxIm;
import com.vf.admin.client.tx.vo.UserShiZhi;
import com.vf.admin.client.tx.vo.userSignVo;
import com.vf.admin.common.BaseController;
import com.vf.admin.common.Constants;
import com.vf.admin.common.entity.Result;
import com.vf.admin.common.splitpage.SplitPageBean;
import com.vf.admin.miaodong.dao.AfterRealNameDao;
import com.vf.admin.miaodong.entity.*;
import com.vf.admin.miaodong.service.AfterInvitationRecordService;
import com.vf.admin.miaodong.service.AfterRealNameService;
import com.vf.admin.miaodong.service.AfterSystemService;
import com.vf.admin.miaodong.service.AfterUserService;
import com.vf.admin.utils.StringEx;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.vf.admin.utils.StringEx.isNull;

/**
 * 实名认证管理
 */
@Controller
@RequestMapping("/after/realname")
public class AfterRealNameController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    AfterRealNameService afterRealNameService;
    @Autowired
    AfterUserService afterUserService;
    @Autowired
    AfterSystemService afterSystemService;
    @Autowired
    AppTaskRecordService appTaskRecordService;
    @Autowired
    AppInvitationRecordService appInvitationRecordService;
    @Autowired
    AppSetupService appSetupService;
    @Autowired
    AppMingxiJinbiService appMingxiJinbiService;

    /**
     * 实名认证列表
     *
     * @param splitPage
     * @param name      真实姓名
     * @return
     */
    @RequestMapping("/list")
    public String list(SplitPageBean splitPage, String phone, String name, Integer status, String startdate, String enddate) {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("name", name);
            map.put("phone", phone);
            map.put("status", status);
            map.put("startdate", startdate);
            map.put("enddate", enddate);
            map.put("shiming", 1);
            Map<Integer, String> statustypeMap = Constants.getstatusType();//审核状态
            List<AppRealName> all = afterRealNameService.findList(map, splitPage);
            request.setAttribute("loginname", phone);
            request.setAttribute("name", name);
            if (StringEx.isNotNull(status)) {
                request.setAttribute("status", status);
            }
            request.setAttribute("list", all);
            request.setAttribute("name", name);
            request.setAttribute("phone", phone);
            request.setAttribute("startdate", startdate);
            request.setAttribute("enddate", enddate);
            request.setAttribute("splitPage", splitPage);
            request.setAttribute("statustypeMap", statustypeMap);
            return this.sucess("/web/after/realname/list");
        } catch (Exception e) {
            logger.error("实名认证列表异常", e);
            return this.error("系统繁忙");
        }
    }


    /**
     * 审核实名  通过拒绝
     *
     * @param id
     * @param state
     * @return
     */
    @RequestMapping("/upState")
    @ResponseBody
    public Result upState(Integer id, Integer state,String remark) {
        try {
            if (isNull(id)) {
                return this.errorJSON("获取ID为空");
            }
            AppRealName appRealName = afterRealNameService.get(id);
            appRealName.setStatus(state);
            afterRealNameService.save(appRealName);
            if (state == 1) {
                afterUserService.upstateShiming(appRealName.getUserid(), 1);
                if(!isNull(appRealName.getShipinstate())) {
                    if (appRealName.getShipinstate() == 1) {
                        //通过  修改用户视频直播权限
                        afterUserService.upstateVideoStatus(appRealName.getUserid(), 1);
                    }
                }
                //添加实名任务
                AppTaskRecord taskRecord = appTaskRecordService.getByTaskId(appRealName.getUserid(), Constants.shiming_task);
                if (org.springframework.util.StringUtils.isEmpty(taskRecord)) {
                    //appTaskRecordService.addTaskRecord(appRealName.getUserid(), Constants.shiming_task);
                }
                //给上级奖励
                AppInvitationRecord invitationRecord = appInvitationRecordService.getShangji(appRealName.getUserid());
                if (!StringUtils.isEmpty(invitationRecord)) {
                    AppSetup setup = appSetupService.get();
                    //增加上级邀请人金币
                    afterUserService.updatejinbi(invitationRecord.getPuserid(), new BigDecimal(setup.getRenzhengfanli().toString()));
                    //增加金币明细
                    appMingxiJinbiService.addMingxi(invitationRecord.getPuserid(),new BigDecimal(setup.getRenzhengfanli()),1,"下级实名认证返利");
                }
                AppUser user=afterUserService.get(appRealName.getUserid());
                //获取用户腾讯方最新的数据
                String re = TxIm.portraitGget(user.getTengxuncode());
                Integer headHalo = 0;
                Integer charmNum = 0;
                if (!isNull(re)) {
                    JSONObject jsonObject1 = JSON.parseObject(re);
                    headHalo = jsonObject1.getInteger("headHalo");
                    charmNum = jsonObject1.getInteger("charmNum");
                }
                //重新设置资料
                userSignVo vo1 = new userSignVo();
                vo1.setId(user.getId());
                vo1.setCharmNum(charmNum);
                vo1.setHeadWear("");
                vo1.setHeadHalo(headHalo);
                vo1.setNobleid(user.getNobleid());
                vo1.setStatus(1);
                net.sf.json.JSONObject obj1 = net.sf.json.JSONObject.fromObject(vo1);
                UserShiZhi shiZhi = new UserShiZhi();
                shiZhi.setUserSign(obj1.toString());
                shiZhi.setTengxuncode(user.getTengxuncode() + "");
                TxIm.portraitSet(shiZhi);
            }else{
                AppMessageRecord messageRecord=new AppMessageRecord();
                messageRecord.setLeixing(2);
                messageRecord.setUserid(appRealName.getUserid());
                messageRecord.setState(1);
                messageRecord.setCreatetime(new Date());
                messageRecord.setTitle("实名认证驳回");
                messageRecord.setMessage("您的实名认证未通过审核,<br>驳回原因："+remark+"<br>请根据驳回原因进行修改");
                afterSystemService.save(messageRecord);
            }

            return this.sucessJSON("操作成功");
        } catch (Exception e) {
            logger.error("审核实名异常", e);
            return this.errorJSON("系统繁忙");
        }
    }


    /**
     * 视频认证列表
     *
     * @param splitPage
     * @param name      真实姓名
     * @return
     */
    @RequestMapping("/videolist")
    public String videolist(SplitPageBean splitPage, String phone, String name, Integer status,Integer videostatus, String startdate, String enddate) {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("name", name);
            map.put("phone", phone);
            map.put("status", status);
            map.put("videostatus", videostatus);
            map.put("startdate", startdate);
            map.put("enddate", enddate);
            map.put("shipin", 1);
            Map<Integer, String> statustypeMap = Constants.getstatusType();//审核状态
            List<AppRealName> all = afterRealNameService.findList(map, splitPage);
            request.setAttribute("loginname", phone);
            request.setAttribute("name", name);

            request.setAttribute("status", status);
            request.setAttribute("videostatus", videostatus);
            request.setAttribute("list", all);
            request.setAttribute("name", name);
            request.setAttribute("phone", phone);
            request.setAttribute("startdate", startdate);
            request.setAttribute("enddate", enddate);
            request.setAttribute("splitPage", splitPage);
            request.setAttribute("statustypeMap", statustypeMap);
            return this.sucess("/web/after/realname/videolist");
        } catch (Exception e) {
            logger.error("频认证列表异常", e);
            return this.error("系统繁忙");
        }
    }

    /**
     * 获取视频认证详情
     *
     * @return
     */
    @RequestMapping("/videoDetail")
    public String videoDetail(Integer id) {
        try {
            AppRealName realName = afterRealNameService.get(id);
            Map<Integer, String> statustypeMap = Constants.getstatusType();//审核状态
            request.setAttribute("statustypeMap", statustypeMap);
            request.setAttribute("realName", realName);
            return this.sucess("/web/after/realname/videoEdit");
        } catch (Exception e) {
            logger.error("系统异常", e);
            return this.error("系统异常");
        }
    }


    /**
     * 审核视频认证  通过拒绝
     *
     * @param id
     * @param state
     * @return
     */
    @RequestMapping("/upVideoState")
    @ResponseBody
    public Result upVideoState(Integer id, Integer state,String remark) {
        try {
            if (isNull(id)) {
                return this.errorJSON("获取ID为空");
            }
            AppRealName appRealName = afterRealNameService.get(id);
            appRealName.setShipinstate(state);
            afterRealNameService.save(appRealName);
            if (state == 1) {
                afterUserService.upstateShipin(appRealName.getUserid(), 1);
                if(!isNull(appRealName.getStatus())) {
                    if (appRealName.getStatus() == 1) {
                        //通过  修改用户视频直播权限
                        afterUserService.upstateVideoStatus(appRealName.getUserid(), 1);
                    }
                }
                //添加实名任务
                AppTaskRecord taskRecord = appTaskRecordService.getByTaskId(appRealName.getUserid(), Constants.shipin_task);
                System.err.println(org.springframework.util.StringUtils.isEmpty(taskRecord));
                if (org.springframework.util.StringUtils.isEmpty(taskRecord)) {
                    //appTaskRecordService.addTaskRecord(appRealName.getUserid(), Constants.shipin_task);
                }
            }else{
                AppMessageRecord messageRecord=new AppMessageRecord();
                messageRecord.setLeixing(2);
                messageRecord.setUserid(appRealName.getUserid());
                messageRecord.setState(1);
                messageRecord.setCreatetime(new Date());
                messageRecord.setTitle("视频认证驳回");
                messageRecord.setMessage("您的视频认证未通过审核,<br>驳回原因："+remark+"<br>请根据驳回原因进行修改");
                afterSystemService.save(messageRecord);
            }
            return this.sucessJSON("操作成功");
        } catch (Exception e) {
            logger.error("审核实名异常", e);
            return this.errorJSON("系统繁忙");
        }
    }
}
